<template>
    <div id="footbar" class="footbar">
      	<div class="input-area">
            <upload-img @choosePicture="choosePicture" @ablumSelected="ablumSelected"></upload-img>
            <img class="emoji" @click.prevent="selectEmoji" src="../assets/look.png">
            <div contenteditable="true" ref="editArea" id="editArea" class="input" @focus="inputFocus" @click.prevent="click" @blur="blur"></div>
			<button class="send" @click="send">发送</button>
      	</div>
        <div class="emoji-area" v-show="emojiVisible">
            <div class="emoji-container">
                <swiper :options="swiperOption" style="height:100%;padding-bottom: 20px;">
                    <swiper-slide v-for="(slide, index) in swiperSlides" :key="index">
                        <ul>
                            <li v-for="emoji in slide" :key="emoji.id">
                                <img @click="addImage" :chinese="emoji.ChineseCon" :src="require(`../assets/emoji/${emoji.ExpressionUrl}.gif`)">
                            </li>
                        </ul>
                    </swiper-slide>
                    <div class="swiper-pagination" slot="pagination"></div>
                </swiper>
            </div>
        </div>
        <div id="footBarBottom" style="height:1px; overflow:hidden"></div>
        <div id="haha" class="headerBox"></div>
    </div>    
</template>
<script>
import emojiConfig from "../config/emoji.js";
import "swiper/dist/css/swiper.css";
import { swiper, swiperSlide } from "vue-awesome-swiper";
import uploadImg from "./uploadImg/uploadImg.vue";
import * as tool from "../utils/tool.js";
import { setTimeout } from 'timers';

export default {
  components: {
    swiper,
    swiperSlide,
    uploadImg
  },
  props: {
    userInfo: {}
  },
  data() {
    return {
      emojiVisible: false,
      keyWord: "",
      emojiConfig: emojiConfig,
      emojiPageSize: 31,
      swiperOption: {
        direction: "horizontal",
        loop: true,
        pagination: {
          el: ".swiper-pagination"
        }
      },
      range: {},
	  selection: {},
	  focusSlient:false
    };
  },
  computed: {
    swiperSlides() {
      let pages = Math.ceil(this.emojiConfig.length / this.emojiPageSize);
      let gift = [];
      let content = [];
      for (let index = 0; index < pages; index++) {
        if (index == pages.length - 1) {
          content = this.emojiConfig.slice(
            index * this.emojiPageSize,
            this.emojiConfig.length
          );
          gift.push(content);
        } else {
          content = this.emojiConfig.slice(
            index * this.emojiPageSize,
            (index + 1) * this.emojiPageSize
          );
          gift.push(content);
        }
      }
      return gift;
    }
  },
  methods: {
      showEmojiBar(isShow){
          this.emojiVisible = isShow
      },
	  choosePicture() {
		console.log('点击了发送图片');
    	this.$refs["editArea"].focus()
	  },
    ablumSelected(imgUrl) {
      let postBody = {
        senderFullName: this.userInfo.FullName,
        toFullName: null,
        senderTime: tool.getTime(),
        content: [
          {
            type: "rtx_img",
            rtx_text: null,
            rtx_img: { url: imgUrl },
            rtx_file: null,
            rtx_smiley: null,
            rtx_app_text_link: null
          }
        ]
      };
      this.$http
        .post("/ChatService/UserPageMessage/ClientSendMessage", postBody)
        .then(function(res) {
          // console.log(res);
        });

      this.$emit("addMessage", {
        isClient: true,
        ...postBody
      });
      this.$emit("needScrollToBottom");
    },
    messageBoxTouch() {
      this.emojiVisible = false;
      this.$refs["editArea"].blur();
    },
    inputFocus() {
        this.$emit("inputFocus")
	},
	click(e) {
		//先删除虚拟光标
		let guangbiao = document
			.querySelector(".input")
			.querySelector(".headerBox");
		if (guangbiao != null) {
			this.$refs["editArea"].removeChild(guangbiao);
		}

		//range更新到点击的位置 点到图片就根据点击位置和图片大小设置一个合理的位置(前或后)
		this.emojiVisible = false;
		let node = e ? e.target : {};

		if (node.tagName === "IMG") {
			this.setCursor(node, e.offsetX < node.width / 2, true);
			e.preventDefault();
		} else if (node.tagName === "DIV") {
			// this.$refs["editArea"].focus();
		}
    },
    blur() {
      //每次焦点移出都要保存一次当前 range ，后面好放回来 由于输入框以外的点击都会使输入框失去焦点，不知道会有什么操作，故勤保存
      let selection = document.getSelection();
      if (selection.anchorNode != null) {
        this.range = this.selection.getRangeAt(0);
      }
      this.$emit('editAreaBlur')
	  //输入法的“完成”按钮，也会触发失焦
	  let _this = this
	  setTimeout(()=>{
		  if (_this.emojiVisible ==false && _this.focusSlient==false) {
			_this.$emit('shurufaDone')
		}
	  },0)
	  
    },
    removeCursorDiv() {
      let guangbiao = this.$refs["editArea"].querySelector(".headerBox");
      if (guangbiao != null) {
        this.$refs["editArea"].removeChild(guangbiao);
      }
    },
    addImage(e) {
      /**
       * 点击emoji图片后，复制节点添到当前range里并设置光标和更新range
       * 若是点到其他地方则设置到之前的位置
       */
      // if (e.target.tagName === 'IMG') {
      //阻止默认事件，微信会执行放大功能
      e.preventDefault();

      let node = e.target.cloneNode(true);

      // let guangbiao = document
      //   .querySelector(".edit-area")
      //   .querySelector(".headerBox");
      // if (guangbiao != null) {
      //   this.$refs["editArea"].removeChild(guangbiao);
      // }
      this.removeCursorDiv(); //有可能输入框中还有伪光标元素

      let cursor = document.getElementById("haha").cloneNode(true);
      cursor.setAttribute("style", "display: inline-block !important");
      this.range.insertNode(cursor);
      this.range.insertNode(node);
      this.setCursor(node, false, false);
      // } else {
      // this.setCursor()
      // }
    },
    setCursor(node, before, needSet) {
      /**
       * node 为传入的节点，不传则foucs到之前保存的位置
       * before 控制折叠方向
       */
      if (node) {
        // 需要新建一个range来添加内容
        let range = document.createRange();
        range.selectNode(node);

        range.collapse(!!before);
        this.selection.removeAllRanges();
        if (needSet == true) {
          this.selection.addRange(range);
        }
        // this.selection.addRange(range)

        // range = this.selection.getRangeAt(0)

        // let cursor = document.getElementById('haha')
        // range.insertNode(cursor)

        // 更新 range
        this.range = range;
      } else {
        this.selection.removeAllRanges();
        // 使用之前的
        this.selection.addRange(this.range);
      }
    },
    selectEmoji() {
		this.emojiVisible = !this.emojiVisible;
		this.$emit("emojiBarChange",this.emojiVisible);
      
		let guangbiao = document
			.querySelector(".input")
			.querySelector(".headerBox");
		if (guangbiao != null) {
			this.$refs["editArea"].removeChild(guangbiao);
		}
		let cursor = document.getElementById("haha").cloneNode(true);
		cursor.setAttribute("style", "display: inline-block !important");
		this.range.insertNode(cursor);
    },
    album() {
      console.log("发送相册");
    },
    send(e) {
        this.removeCursorDiv(); //有可能输入框中还有伪光标元素
        let messageContent = this.$refs["editArea"].innerHTML.replace(/&nbsp;/g,'').trim()
        // console.log('发送...................')
        // console.log(this.$refs["editArea"].innerHTML);
        // console.log(messageContent); 
        // console.log(messageContent.length); 
        
        this.$refs["editArea"].focus()
        
        if (messageContent.length == 0) {
            return;
        }

        //先切入一下焦点
        this.focusSlient = true
        let _this = this
        this.$refs["editArea"].focus()
        setTimeout(()=>{
            _this.focusSlient = false
        },200)
        //把消息输入框拉到最下面
        // setTimeout(()=>{
        // },2000)

      //发送后端接口的时候，需要把表情图片解析成标识符
      let reg = new RegExp('<img.*?chinese="(.*?)" src=".*?">', "g");
      let messageToSend = messageContent.replace(reg, "$1");

      let postBody = {
        senderFullName: this.userInfo.FullName,
        toFullName: null,
        senderTime: tool.getTime(),
        content: [
          {
            type: "rtx_text",
            rtx_text: { text: messageToSend },
            rtx_img: null,
            rtx_file: null,
            rtx_smiley: null,
            rtx_app_text_link: null
          }
        ]
      };
      	this.$http.post("/ChatService/UserPageMessage/ClientSendMessage", postBody).then(function(res) {
          // console.log(res);
        });
        
      this.$emit("addMessage", {
        isClient: true,
        ...postBody
      });
      this.emojiVisible = false;
	  this.$refs["editArea"].innerHTML = "";
    //   this.$refs["editArea"].focus()
    //   e.preventDefault();
    }
  },
  mounted() {
    // 先得到selection，并创建一个range
    this.selection = document.getSelection()
    // this.range = document.createRange()
    this.$refs["editArea"].focus()
    this.range = this.selection.getRangeAt(0)
    this.$refs["editArea"].blur()
  }
};
</script>
<style lang="scss" scoped>
.footbar {
  position: absolute;
  width: 100%;

  // height: 100px;
  // padding: 10px 0px;
  bottom: 0px;
  // border: 1px solid green;
.input-area {
	// display: flex;
	// height: 40px;
	// padding: 10px;
	padding-right: 5px;
	font-size: 0px;
	// align-items: flex-end;
	background-color: #F7F7F7;
	.input {
		// flex: 1;
		display: inline-block;
		background-color: #ffffff;
		min-height: 34px;
		max-height: 90px;
		overflow: auto;
		border-radius: 5px;
		vertical-align: middle;
		margin-right: 10px;
		outline: none;
		font-size: 16px;
		padding-left: 10px;
		padding-top: 6px;
		width: calc(100% - 147px);
		img {
    		vertical-align: middle;
			pointer-events: none;
		}
	}
    .emoji {
      	width: 30px;
		height: 30px;
		padding: 10px 10px 10px 0px;
		box-sizing: content-box;
		vertical-align: middle;
    }
	.send {
		background-color: #08BF5F;
		border: none;
		color: #ffffff;
		height: 30px;
		line-height: 30px;
		border-radius: 4px;
		text-align: center;
		width: 54px;
		padding: 0px;
		font-size: 16px;
		letter-spacing: 2px;
		vertical-align: middle;
	}
  }
  .emoji-area {
    height: 333px;
    background-color: #ffffff;
    transition: opacity 0.3s ease-in-out;
    .emoji-container {
      padding: 40px 10px 0px 10px;
      ul {
        margin: 0;
        padding: 0;
        li {
          list-style: none;
          float: left;
          width: 14.28%;
          margin-bottom: 20px;
          text-align: center;
          img {
            width: 30px;
          }
        }
      }
      .swiper-pagination {
        margin-top: 20px;
      }
    }
  }

  @keyframes blink {
    0%,
    100% {
      background-color: #519dfb;
      /* color: #aaa; */
    }
    50% {
      background-color: #ffffff; /* not #aaa because it's seem there is Google Chrome bug */
      /* color: #000; */
    }
  }

  .headerBox {
    display: none;
    vertical-align: middle;
    /* padding: 10px; */
    font-size: 15px;
    width: 2px;
    // background-color: #519DFB;
    // border: 1px solid #519DFB;
    height: 24px;
    animation: blink 1s infinite steps(1, start);
    // -webkit-animation: fade 1500ms infinite;
  }
}
</style>
